package com.yuncheng.spcyApi.flow;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.spcyApi.mapper.SpcyKpYbjcyMapper;
import com.yuncheng.spcyApi.vo.flow.SpcyJobXqVo;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.*;
import com.yuncheng.spcyApi.vo.flow.AgentVo;
import com.yuncheng.vo.CurrentUserVo;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.spcy.SpcyReturnVo;
import com.yuncheng.spcyApi.vo.sqsx.SqsxZbrVo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 见习考评流程（预备检查员考评）
 * @author hua
 */
@Component(value = "jcyYbkpFlowService")
public class JcyYbkpFlowService {
    private static final Logger log = LoggerFactory.getLogger(JcyYbkpFlowService.class);

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private IYcSysUserService ycSysUserService;

    @Resource
    @Lazy
    private ISpcyRsHcyService spcyRsHcyService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    @Lazy
    private ISpcyKpYbjcyService spcyKpYbjcyService;

    @Resource
    @Lazy
    private ISysFlowNodeService sysFlowNodeService;

    @Resource
    @Lazy
    private FlowNodeService flowNodeService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    @Resource
    private SpcyKpYbjcyMapper spcyKpYbjcyMapper;

    /**
     * 处理流程
     * @param flowVo
     * @param jobId
     * @param submitType
     * @param opinion
     * @return
     */
    public Result handleFlow(FlowVo flowVo, String jobId, String pid, String submitType, String opinion){
        if (StringUtils.isBlank(jobId)){
            throw new BusinessException("流程任务参数为空！");
        }
        // 当前流程任务
        SpcySqsxJob nowJob = spcySqsxJobService.getById(jobId);;

        if (nowJob == null){
            return Result.error("当前流程任务不存在，请重试");
        }

        pid = nowJob.getFpid();
        if (StringUtils.isBlank(pid)){
            throw new BusinessException("业务参数为空！");
        }

        // 提交按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)) {
            if (nowJob == null) {
                return Result.error("当前流程任务不存在");
            }
        }

        // 个人总结
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT) && nowJob.getFhjmc().equals(SpcyFlowConstant.YBKP_HJMC_GRZJ)){
            /*SpcyKpYbjcy ybjcy = spcyKpYbjcyService.getById(pid);
            if (ybjcy == null){
                return Result.error("当前预备检查员考评记录不存在，请联系管理员");
            }*/
        }

        // 流程环节处理
        Result httpResult = handleNodeName(flowVo, submitType, nowJob, pid, opinion);
        if (!httpResult.isSuccess()){
            return httpResult;
        }else {
            /*if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT) && nowJob.getFhjmc().equals(SpcyFlowConstant.YBKP_HJMC_JBRSH)){
                // 预备检查员晋升-组员
//                this.promoteYbjcy(pid,nowJob.getFhjmc());

            }else*/
            if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT) && nowJob.getFhjmc().equals(SpcyFlowConstant.YBKP_HJMC_END)) {
                SpcyKpYbjcy ybjcy = spcyKpYbjcyService.getById(pid);
                ybjcy.setFlczt(SpcyFlowConstant.LCZT_LCBJ);
                ybjcy.setFwcsj(new Date());
                spcyKpYbjcyService.updateById(ybjcy);

                spcySqsxXpjlService.updateYbKpjgByJcy(ybjcy.getFjcyid(), ybjcy.getFsqsxid(), ybjcy.getFpj());
            }
        }
        return httpResult;
    }

    /**
     * 流程环节处理
     * @param pid 业务id
     * @param flowVo 需要修改的字段内容
     * @param job 流程任务job
     * @param opinion 办理意见
     * @param submitType 提交、保存类型
     * @return true(),false(提示信息)
     */
    public Result handleNodeName(FlowVo flowVo,String submitType, SpcySqsxJob job, String pid, String opinion){
        HashMap<String, Object> map = flowVo.getMap();
        String smgflag = flowVo.getSmgflag(); // 短信发送标志
        String smsContent = flowVo.getSmsContent(); // 发送短信内容

        Result res = null;

        // 保存按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)){
            Result result = this.updateKpxx(pid, map);
            if (!result.isSuccess()){
                return result;
            }
        }

        // 提交按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)){
            Result result = this.updateKpxx(pid, map);
            if (!result.isSuccess()){
                return result;
            }

            if (job == null){
                throw new BusinessException("当前流程任务不存在！");
            }

            if (StringUtils.isBlank(job.getFhjmc())){
                throw new BusinessException("当前流程任务环节名称丢失！");
            }

            // 流程任务id
            String jobid = job.getId();

            // 提交流程任务,待办人是否为空，指定待办人
            if (StringUtils.isBlank(flowVo.getDbrid())) {
                // 按审查模式-提交-流程任务
                res = this.passJob(pid, jobid, job, opinion, flowVo.getNextNode(),flowVo.getNextNodeId(), null);
            }else {
                // 按审查模式-提交-流程任务
                res = this.passJob(pid, jobid, job, opinion, flowVo.getNextNode(),flowVo.getNextNodeId(),flowVo.getDbrid());
            }

            if (!res.isSuccess()){
                return res;
            }else {
                /**
                 * 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
                 * 发送下环节短信
                 */
                if (StringUtils.isNotBlank(smgflag) && (smgflag.equals("是") || smgflag.equals("true"))){
                    busService.sendSmsToNextJob(jobid,smsContent);
                }
            }
        }

        return Result.ok("提交成功");
    }

    /**
     * 同步移除-预备检查员流程
     */
    public void syncDelYbjcyFlow(String sqsxid, String fuserid){
        List<SpcyKpYbjcy> list = spcyKpYbjcyService.list(new LambdaQueryWrapper<SpcyKpYbjcy>()
                .eq(SpcyKpYbjcy::getFsqsxid, sqsxid)
                .eq(SpcyKpYbjcy::getFuserid, fuserid));

        for (SpcyKpYbjcy bean : list) {
            // 删除流程待办
            spcySqsxJobService.remove(new LambdaQueryWrapper<SpcySqsxJob>()
                    .eq(SpcySqsxJob::getFpid, bean.getId())
            );

            spcyKpYbjcyService.removeById(bean.getId());
        }

    }

    /**
     * 同步更新-预备检查员流程-组长信息
     * */
    public void syncUpdateZzInfo(String sqsxid){
        List<String> ybIdList = spcyKpYbjcyMapper.selectIdListByFsqsxid(sqsxid);
        if (CollectionUtil.isEmpty(ybIdList)) {
            return;  // 没有预备
        }

        List<SpcySqsxXpjl> zzList = spcySqsxXpjlService.list(new LambdaQueryWrapper<SpcySqsxXpjl>()
                .eq(SpcySqsxXpjl::getFsqsxid, sqsxid)
                .eq(SpcySqsxXpjl::getFsftyxp, SpcyConstant.XPJL_SFTYXP_YES)
                .eq(SpcySqsxXpjl::getFssk, SpcyConstant.HCY_SSK_ZZ)
        );
        if (CollectionUtil.isEmpty(zzList)){
            return;
        }

        String zzids = "";
        String zzmcs = "";
        // 拿到选派的组长
        for (SpcySqsxXpjl xpjl : zzList){
            if (StringUtils.isNotBlank(zzids)){
                zzids += "," + xpjl.getFuserid();
                zzmcs += "," + xpjl.getFjcyxm();
            }else {
                zzids += xpjl.getFuserid();
                zzmcs += xpjl.getFjcyxm();
            }
        }

        // 更新组长信息
        LambdaUpdateWrapper<SpcyKpYbjcy> updateInfoWq = new LambdaUpdateWrapper<>();
        updateInfoWq.eq(SpcyKpYbjcy::getFsqsxid, sqsxid);

        SpcyKpYbjcy updateInfo = new SpcyKpYbjcy();
        updateInfo.setFzzid(zzids);
        updateInfo.setFzzxm(zzmcs);
        spcyKpYbjcyService.update(updateInfo, updateInfoWq);

        /** 更新组长流程信息 */
        LambdaUpdateWrapper<SpcySqsxJob> updateJobWq = new LambdaUpdateWrapper<>();
        updateJobWq.in(SpcySqsxJob::getFpid, ybIdList);
        updateJobWq.eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.YBKP_HJMC_ZZPJ);

        SpcySqsxJob updateJob = new SpcySqsxJob();
        updateJob.setFdbrid(zzids);
        updateJob.setFdbr(zzmcs);

        updateJob.setFydbrid(zzids);
        updateJob.setFydbr(zzmcs);
        spcySqsxJobService.update(updateJob, updateJobWq);


    }

    /** 同步更新-预备检查员流程-检查日期 */
    public void syncUpdateJcsjInfo(String sqsxid, Date jckssj, Date jcjssj){
        if (jckssj == null || jcjssj == null){
            return;
        }

        String jcsj = DateConversionUtils.DateToStringYYYYMMDD(jckssj);
        jcsj += "至";
        jcsj += DateConversionUtils.DateToStringYYYYMMDD(jcjssj);

        LambdaUpdateWrapper<SpcyKpYbjcy> updateInfoWq = new LambdaUpdateWrapper<>();
        updateInfoWq.eq(SpcyKpYbjcy::getFsqsxid, sqsxid);

        SpcyKpYbjcy updateInfo = new SpcyKpYbjcy();
        updateInfo.setFjcsj(jcsj);
        spcyKpYbjcyService.update(updateInfo, updateInfoWq);
    }

    /**
     * 添加预备检查员 - 初始化流程
     * @param sqsxid
     */
//    @Async(value = "asyncNormalTask")
    public void joinYbJcyJob(String sqsxid){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();

        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx == null){
            log.error("申请事项【{}】为空",sqsxid);
            return;
        }

        List<SpcySqsxXpjl> tyXpXpjlList = busService.getTyXpXpjlList(sqsxid, SpcyConstant.FLOW_TYPE_CY);
        if (CollectionUtils.isEmpty(tyXpXpjlList)){
            return;
        }
        List<SpcySqsxXpjl> ybList = tyXpXpjlList.stream().filter(x -> StringUtils.isNotBlank(x.getFssk())
                && x.getFssk().equals(SpcyConstant.HCY_SSK_YB)).collect(Collectors.toList());

        List<SpcySqsxXpjl> zzList = tyXpXpjlList.stream().filter(x -> StringUtils.isNotBlank(x.getFssk())
                && x.getFssk().equals(SpcyConstant.HCY_SSK_ZZ)).collect(Collectors.toList());

        String zzids = "";
        String zzmcs = "";
        // 拿到选派的组长
        if (CollectionUtils.isNotEmpty(zzList)){
            for (SpcySqsxXpjl xpjl : zzList){
                if (StringUtils.isNotBlank(zzids)){
                    zzids += ","+xpjl.getFuserid();
                    zzmcs += ","+xpjl.getFjcyxm();
                }else {
                    zzids += xpjl.getFuserid();
                    zzmcs += xpjl.getFjcyxm();
                }
            }
        }

        if (StringUtils.isBlank(zzids)){
            return;
        }

        // 初始化记录
        if (CollectionUtils.isNotEmpty(ybList)){
            for (SpcySqsxXpjl xpjl : ybList) {

                List<SpcyKpYbjcy> isExistList = spcyKpYbjcyService.list(new LambdaQueryWrapper<SpcyKpYbjcy>()
                        .eq(SpcyKpYbjcy::getFsqsxid, sqsxid)
                        .eq(SpcyKpYbjcy::getFuserid, xpjl.getFuserid()));
                if (CollectionUtils.isNotEmpty(isExistList)){
                    continue;
                }

                String ybid = GetUuIdUtils.ReplaceUuId();
                SpcyKpYbjcy ybjcy = new SpcyKpYbjcy();
                ybjcy.setId(ybid);
                ybjcy.setFjcyid(xpjl.getFjcyid());
                ybjcy.setFuserid(xpjl.getFuserid());
                ybjcy.setFjcyxm(xpjl.getFjcyxm());
                ybjcy.setFsqsxid(sqsxid);
                ybjcy.setFzzid(zzids);
                ybjcy.setFzzxm(zzmcs);
                ybjcy.setFgzdw(xpjl.getFgzdw());
                ybjcy.setFkssj(new Date());
                ybjcy.setFcyjcfw(sqsx.getFcyjcfw());

                String jcsj = "";
                if (sqsx.getFcykssj() != null && sqsx.getFcyjssj() != null) {
                    jcsj = DateConversionUtils.DateToStringYYYYMMDD(sqsx.getFcykssj()) + "至" + DateConversionUtils.DateToStringYYYYMMDD(sqsx.getFcyjssj());
                }
                ybjcy.setFjcsj(jcsj);
                ybjcy.setFqymc(sqsx.getFqymc());
                ybjcy.setFjclx(sqsx.getFjclx());
                StringBuffer jcyzj = new StringBuffer();
                jcyzj.append("<p>&nbsp;一、检查基本情况</p>\n" +
                        "<p>（包括对被检查对象（品种）的基本了解）</p>\n" +
                        "<p>二、承担的检查任务</p>\n" +
                        "<p>（简述承担的检查任务）</p>\n" +
                        "<p>三、完成的情况</p>\n" +
                        "<p>（结合承担的检查任务，简述检查的思路和检查关注 的重点）</p>\n" +
                        "<p>四、体会与收获</p>\n" +
                        "<p>（对检查的深入了解，对企业质量管理方面。</p>\n" +
                        "<p>五、认知和思考</p>\n" +
                        "<p>（对检查存在问题的思考、对团队合作以及检查思路 的体会与收获等）。</p>\n" +
                        "<p>六、意见与建议</p>\n" +
                        "<p>（对检查的组织、检查方案、检查的形式等方面均可 提出意见与建议）</p>");
                ybjcy.setFsxjcyzj(jcyzj.toString());
                ybjcy.setFlczt(SpcyFlowConstant.LCZT_LCZB);

                // 存在流程-删除
                /*List<SpcyKpYbjcy> isExistList = spcyKpYbjcyService.list(new LambdaQueryWrapper<SpcyKpYbjcy>()
                        .eq(SpcyKpYbjcy::getFsqsxid, sqsxid)
                        .eq(SpcyKpYbjcy::getFuserid, ybjcy.getFuserid()));
                if (CollectionUtils.isNotEmpty(isExistList)){
                    continue;
                    *//*for (SpcyKpYbjcy ybjcy1 : isExistList){
                        spcyKpYbjcyService.removeById(ybjcy1.getId());
                        spcySqsxJobService.remove(new LambdaQueryWrapper<SpcySqsxJob>().eq(SpcySqsxJob::getFpid,ybjcy1.getId()));
                    }*//*
                }*/
                spcyKpYbjcyService.save(ybjcy);

                this.createProcess(ybid,currentUser,false); // 初始化-预备检查员流程
            }
        }
    }

    /**
     * 初始化流程
     * @param pid 业务id
     * @param currentUser 当前登陆用户
     * @param isSendSms 是否发送短信
     * @return
     */
    public Result createProcess(String pid, CurrentUserVo currentUser, boolean isSendSms){

        String lcmbCode = SpcyFlowConstant.KP_YBJCY_FLOW_CODE;

        //获取流程模板的第一个环节
        SysFlowTemple code = sysFlowNodeService.getCode(lcmbCode);

        List<SysFlowNode> node = sysFlowNodeService.getFirstNode(code.getId());

        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, pid)
                .eq(SpcySqsxJob::getFnodeid, node.get(0).getId()));
        if (CollectionUtils.isNotEmpty(jobList)){
            return Result.error("当前申请事项环节["+node.get(0).getFjdmc()+"】已经初始化了!");
        }

        Result result = flowNodeService.createJob(lcmbCode,pid,"",node.get(0),null,null,currentUser);
        if (!result.isSuccess()){
            return result;
        }else {
            if (isSendSms) {
                SpcySqsxJob job = (SpcySqsxJob) result.getResult();
                if (job != null) {
                    String nextNodeSmsContent = busService.getNextNodeSmsContent(job, null);
                    busService.sendSmsToNodeDbr(job.getFdbrid(), job.getFlcmc() + "-" + job.getFhjmc(), nextNodeSmsContent);
                }
            }
        }

        return result;
    }

    /**
     * 提交流程
     * @param pid 业务id
     * @param jobid 流程任务id
     * @param job 当前流程任务
     * @param opinion 办理意见
     * @param nextNodeName 下环节结点名称
     * @param nextNodeId 下环节结点id
     * @param nextNodeDbrIds 下环节待办人
     * @return
     */
    private Result passJob(String pid,String jobid,SpcySqsxJob job, String opinion,String nextNodeName,String nextNodeId,String nextNodeDbrIds){
        if (job == null){
            job = spcySqsxJobService.getById(jobid);
        }
        String jobNodeName = job.getFhjmc(); // 当前环节名称

        Result httpResult = null;

        // 是否为最终结点
        if (StringUtils.isNotBlank(jobNodeName) && jobNodeName.equals(SpcyFlowConstant.YBKP_HJMC_END)){
            //办理掉当前环节
            httpResult = flowNodeService.doJob(job, opinion);
        }else {
            httpResult = flowNodeService.passJob(SpcyFlowConstant.KP_YBJCY_FLOW_CODE, pid, jobid, opinion, nextNodeId, nextNodeDbrIds);
        }

        if (!httpResult.isSuccess()){
            return httpResult;
        }

        return Result.ok("success");
    }

    /**
     * 退回流程
     */
    public void getReturnUpperFlowJob(SpcyReturnVo spcyReturnVo){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            throw new BusinessException("登录已失效，请重新登录！");
        }

        if (StringUtils.isBlank(spcyReturnVo.getJobid())){
            throw new BusinessException("流程任务参数为空！");
        }

        if (StringUtils.isBlank(spcyReturnVo.getOpinion())){
            throw new BusinessException("请填写退回意见！");
        }

        SpcySqsxJob currentJob = spcySqsxJobService.getById(spcyReturnVo.getJobid());
        if (currentJob == null){
            throw new BusinessException("退回失败！当前流程任务不存在！");
        }

        SpcySqsxJob previousJob = getCurrentJobPrevious(spcyReturnVo.getJobid(), currentJob);
        if (previousJob == null){
            throw new BusinessException("退回失败！选中的退回环节不存在！");
        }

        // 退回功能
        Result result = flowNodeService.returnJob(spcyReturnVo.getJobid(), currentJob, spcyReturnVo.getShjid(), previousJob, spcyReturnVo.getOpinion(), currentUser);
        if (result.isSuccess()){

            if (StringUtils.isNotBlank(spcyReturnVo.getSmgflag()) && (spcyReturnVo.getSmgflag().equals("是") || spcyReturnVo.getSmgflag().equals("true"))) {
                SpcySqsxJob newPreviousJob = (SpcySqsxJob) result.getResult();
                // 发送退回短信
                String nextNodeSmsContent = busService.getNextNodeSmsContent(newPreviousJob, null);
                busService.sendNextNodeSmsContent(newPreviousJob, nextNodeSmsContent);
            }
        }
    }

    /**
     * 查询审评查验流程当前环节-上一环节
     * @param jobid 流程任务id
     * @return
     */
    private SpcySqsxJob getCurrentJobPrevious(String jobid, SpcySqsxJob nowJob){
        if (StringUtils.isBlank(jobid)){
            throw new BusinessException("流程任务参数为空！");
        }
        SpcySqsxJob previousJob = null;

        if (nowJob == null) {
            nowJob = spcySqsxJobService.getById(jobid);
            if (nowJob == null) {
                throw new BusinessException("当前流程任务不存在！");
            }
        }

        if (StringUtils.isBlank(nowJob.getFnodeid())){
            throw new BusinessException("当前流程任务结点配置不存在！");
        }

        List<SysFlowNode> previousNodeList = sysFlowNodeService.getPreviousNode(nowJob.getFnodeid());
        if (CollectionUtil.isEmpty(previousNodeList)){
            return previousJob;
        }

        LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxJob::getFpid, nowJob.getFpid());
        queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);

        if (previousNodeList.size() == 1) {
            queryWrapper.eq(SpcySqsxJob::getFnodeid, previousNodeList.get(0).getId());
        }else {
            List<String> preIdsList = previousNodeList.stream().map(SysFlowNode::getId).collect(Collectors.toList());
            queryWrapper.in(SpcySqsxJob::getFnodeid, preIdsList);
        }

        // 上环节结点id-办理过的流程任务
        List<SpcySqsxJob> previousJobList = spcySqsxJobService.list(queryWrapper);

        for (int i=0; i<previousJobList.size(); i++){
            previousJob = previousJobList.get(0);
        }

        return previousJob;
    }

    /**
     * 验证预备检查员-参加了几次检查(满足两次-晋升组员)
     */
    private void promoteYbjcy(String ybid,String nodeName){
        SpcyKpYbjcy yb = spcyKpYbjcyService.getById(ybid);
        if (yb == null){
            log.error("预备检查员晋升组员失败，当前预备检查员信息不存在【{}】",ybid);
            return;
        }
        List<SpcyKpYbjcy> countYbjcy = spcyKpYbjcyService.list(new LambdaQueryWrapper<SpcyKpYbjcy>()
                .eq(StringUtils.isNotBlank(yb.getFuserid()),SpcyKpYbjcy::getFuserid, yb.getFuserid())
                .eq(StringUtils.isNotBlank(yb.getFjcyid()),SpcyKpYbjcy::getFjcyid,yb.getFjcyid()));
        if (countYbjcy.size() > 1){
            boolean isPromoting = true;
            for (SpcyKpYbjcy ybjcy : countYbjcy){
                // 是否存在不合格的
                if (StringUtils.isBlank(ybjcy.getFpj()) || ybjcy.getFpj().equals(SpcyConstant.YBJCY_PJ_BHG)){
                    isPromoting = false;
                    break;
                }
            }
            if (isPromoting) {
                SpcyRsHcy rsHcy = spcyRsHcyService.getById(yb.getFjcyid());
                if (rsHcy != null) {
                    rsHcy.setFssk(SpcyConstant.HCY_SSK_ZYK);
                    spcyRsHcyService.updateById(rsHcy);

                    String logNr = "预备检查员晋升组员：【姓名】为[" + yb.getFjcyxm() + "];" +
                            "【所属库】从[预备检查员]设置为[" + SpcyConstant.HCY_SSK_ZYK + "]";
                    spcyLogService.addLogs(nodeName, logNr, ybid, LogConstant.LOGS_RS_HCY, SpcyConstant.LOGS_SYS_TYPE_BC);
                }
            }
        }
    }

    /**
     * 修改预备检查员基本信息
     * @param pid 业务id
     * @param buffer
     * @return
     */
    private Result updateKpxx(String pid,HashMap<String,Object> buffer){
        if (StringUtils.isBlank(pid)){
            return Result.error("预备考评id不能存在");
        }
        SpcyKpYbjcy updateYbjcy = spcyKpYbjcyService.getById(pid);
        if (updateYbjcy == null){
            return Result.error("当前年度考评信息不存在，请重试");
        }
        Map<String, Object> oldMap = ObjectToMapUtils.objectToMap(updateYbjcy);

        // 修改
        ConvertUtils.register(new DateConvert(), java.util.Date.class);
        try {
            BeanUtils.populate(updateYbjcy, buffer);
        }catch (IllegalAccessException e) {
            log.error("出错-保存预备考评【非法访问异常 ，llegalAccessException】,{}",e.getMessage());
        } catch (InvocationTargetException e) {
            log.error("出错-保存预备考评【调用TargetException，InvocationTargetException】,{}",e.getMessage());
        }
        spcyKpYbjcyService.updateById(updateYbjcy);

        String logContent = "基本信息修改: ";
        logContent += LogUtils.BeanModifyMsg(updateYbjcy,oldMap);
        spcyLogService.addLogs(LogConstant.LOGS_KP_YBJCY, logContent, pid, LogConstant.LOGS_KP_YBJCY, SpcyConstant.LOGS_SYS_TYPE_XG);

        return Result.ok();
    }

    /**
     * 获取当前流程任务相关信息
     * @param jobid 流程任务id
     */
    public Map getJobConcernByJobId(String jobid){
        Map map = new HashMap();

        // 当前流转记录
        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        if (job == null){
            log.error("当前流程任务id为【{}】的流转记录不存在",jobid);
            throw new BusinessException("流程任务不存在！");
        }
        String ybid = job.getFpid();
        if (org.apache.commons.lang3.StringUtils.isBlank(ybid)){
            log.error("当前流程任务id为【{}】的流转记录中的预备检查员考评id为空",jobid);
            throw new BusinessException("业务参数为空!");
        }

        // 预备信息
        SpcyKpYbjcy ndkpBasic = spcyKpYbjcyService.getById(ybid);

        // 流程任务流传记录
        /*LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxJob::getFpid, ybid);
        queryWrapper.like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.YBKP_LCMC);
        queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);
        queryWrapper.orderByAsc(SpcySqsxJob::getCreateTime);
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(queryWrapper);*/

        map.put("ybkp",ndkpBasic); // 年度考评基本信息
        map.put("job",job); // 当前流转记录
        map.put("jobHistoryList", spcySqsxJobService.selectHistoryListByFpidAndFlcmc(ybid, null)); // 流程任务流传记录

        // 获取下环节待办人
        map.putAll(this.getNextNodeDbr(jobid,job));

        return map;
    }

    /**
     * 获取APP-获取当前流程任务相关信息
     */
    public Map getAppJobConcernByJobId(String jobid){
        Map map = new HashMap();


        SpcyJobXqVo job = spcySqsxJobService.selectJobInfoById(jobid);
        if (job == null) {
            throw new BusinessException("当前流程任务不存在！");
        }

        map.put("job", job); // 申请事项基本信息
        map.put("ybkp", spcyKpYbjcyService.getById(job.getFpid())); // 当前流转记录
        return map;
    }

    /**
     * 获取下环节待办人
     * @param jobid
     * @param job
     * @return
     */
    private Map getNextNodeDbr(String jobid,SpcySqsxJob job){
        Map map = new HashMap();

        Map nextDbr = this.getNowJobInNextDbrAndHandlePageUrl(jobid, job);
        String nextNodeId = ""; // 下结点id
        String nextNode = "办结"; // 下结点名称
        if (nextDbr.get("nextNode") != null) {
            SysFlowNode nextFlowNode = (SysFlowNode) nextDbr.get("nextNode");
            nextNodeId = nextFlowNode.getId();
            nextNode = nextFlowNode.getFjdmc();
        }
        List<AgentVo> dbrListByMap = this.getDbrListByMap(nextDbr);

        map.put("nextNodeDbrList", dbrListByMap); // 下环节待办人list

        map.put("nextNode", nextNode); // 下流程结点名称
        map.put("nextNodeId", nextNodeId); // 下流程结点id

        return map;
    }

    /**
     * 获取下一个环节名称和待办人
     * @param job 流程任务
     * @param jobid 流程任务id
     * @return
     * {
     *     dbrId
     *     dbr:
     *     nextNode：下流程结点
     *     handlePageUrl：办理页面路径
     * }
     */
    private Map getNowJobInNextDbrAndHandlePageUrl(String jobid, SpcySqsxJob job){
        if (job == null && StringUtils.isNotBlank(jobid)){
            job = spcySqsxJobService.getById(jobid);
        }
        String flowCode = SpcyFlowConstant.KP_YBJCY_FLOW_CODE;
        return flowNodeService.getNowJobInNextDbrAndHandlePageUrl(flowCode, job, null);
    }

    /**
     * 获取当前环节待办人
     * @param pid 业务id
     * @param nodeName 环节名称
     * @return
     */
    public Map getNodeDbr(String pid, String nodeName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        if (nodeName.equals(SpcyFlowConstant.YBKP_HJMC_GRZJ)){
            SpcyKpYbjcy yb = spcyKpYbjcyService.getById(pid);
            if (yb != null){
                dbrId = yb.getFuserid();
                dbr = yb.getFjcyxm();
            }
        }

        if (nodeName.equals(SpcyFlowConstant.YBKP_HJMC_ZZPJ)){
            SpcyKpYbjcy yb = spcyKpYbjcyService.getById(pid);
            if (yb != null){
                dbrId = yb.getFzzid();
                dbr = yb.getFzzxm();
            }
            if (StringUtils.isBlank(dbrId)){
                // 该环节待办人为空，跳转下环节
                if (yb != null && StringUtils.isNotBlank(yb.getFsqsxid())) {
                    Map zbrBySqsxId = getZbrBySqsxId(yb.getFsqsxid());
                    dbrId = zbrBySqsxId.get("dbrId").toString();
                    dbr = zbrBySqsxId.get("dbr").toString();
                }
            }
        }

        if (nodeName.equals(SpcyFlowConstant.YBKP_HJMC_JBRSH)){
            SpcyKpYbjcy yb = spcyKpYbjcyService.getById(pid);
            if (yb != null && StringUtils.isNotBlank(yb.getFsqsxid())) {
                Map zbrBySqsxId = getZbrBySqsxId(yb.getFsqsxid());
                dbrId = zbrBySqsxId.get("dbrId").toString();
                dbr = zbrBySqsxId.get("dbr").toString();
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    /**
     * 获取主办人
     * @param sqsxId 申请事项id
     * @return
     * {
     *     dbrId: 待办人id
     *     dbr: 待办人
     * }
     */
    private Map getZbrBySqsxId(String sqsxId){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        SqsxZbrVo zbrVo = spcySqsxBaiscService.selectFzbrById(sqsxId);
        if (zbrVo != null && StringUtils.isNotBlank(zbrVo.getFzbr())){

            dbrId = zbrVo.getFzbr();

            if (StringUtils.isNotBlank(zbrVo.getFjbrmc())){
                dbr = zbrVo.getFjbrmc();
            }else {
                List<String> userIdList =  StringPatternUtils.getListByIds(zbrVo.getFzbr());
                List<YcSysUser> userList = ycSysUserService.findRealnameListByIds(userIdList);
                for (int i = 0; i<userList.size(); i++){
                    if (StringUtils.isBlank(dbr)) {
                        dbr = userList.get(i).getRealname();
                    } else {
                        dbr += "," + userList.get(i).getRealname();
                    }
                }
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    /**
     * 将待办人map转为List
     * @param map { dbrId: 待办人id ; dbr: 待办人 }
     */
    private List<AgentVo> getDbrListByMap(Map map){
        String dbrids = map.get("dbrId").toString(); // 待办人id
        String dbrs = map.get("dbr").toString(); // 待办人

        List<AgentVo> agentList = new ArrayList<>();

        if (StringUtils.isNotBlank(dbrids)) {
            String agentIds[] = dbrids.split(",|，");
            String agentNames[] = dbrs.split(",|，");

            for (int i = 0; i < agentIds.length; i++) {
                AgentVo agentVo = new AgentVo();
                agentVo.setDbrid(agentIds[i]);
                agentVo.setDbr(agentNames[i]);
                agentList.add(agentVo);
            }
        }

        return agentList;
    }
}
